package fishBids.group3.behaviour.market;

import es.upm.agents.ontology.ToSellProduct;
import es.upm.agents.ontology.ToSellProductResponse;
import fishBids.group3.AgMarket;
import fishBids.group3.common.Constants;
import fishBids.group3.utils.Utils;
import jade.content.lang.Codec;
import jade.content.onto.Ontology;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;

public class MarketSellProductBehaviour extends CyclicBehaviour {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2472621384661749131L;
	
	public MarketSellProductBehaviour(AgMarket agent, Codec codec, Ontology ontology){
		this.agMarket = agent;
		this.codec =  codec;
		this.ontology = ontology;
		
	}

	@Override
	public void action() {

		// Waits for estimation requests
		// Receive the message 
		ACLMessage msg = agMarket.receive(MessageTemplate.and(
				MessageTemplate.MatchPerformative(ACLMessage.REQUEST),
				MessageTemplate.MatchProtocol(Constants.SELL_PRODUCT) )); 

		if (msg != null)

		{
			if (msg.getPerformative() == ACLMessage.REQUEST) {

//					System.out.println( "Market >> Sellproduct request message arrived");
					
					ToSellProduct toSellProduct = (ToSellProduct) Utils.extractContent(this.agMarket, msg);
					
					float itemCost = (Float)this.agMarket.getItemsPrices().get(toSellProduct.getProductType().getType());
					float revenue = itemCost * toSellProduct.getAmount();
					float newItemCost =  itemCost - Utils.calculatePriceDelta( Constants.DECREASE_LOWER_LIMIT,
							Constants.DECREASE_UPPER_LIMIT, toSellProduct.getAmount());
					this.agMarket.getItemsPrices().put(toSellProduct.getProductType().getType(), new Float(newItemCost));
					ToSellProductResponse toSellProductResponse = new ToSellProductResponse();					
					toSellProductResponse.setRevenue(revenue);
////					System.out.println("Market >>Sell product, product type: " + toSellProduct.getProductType().getType() +
//							" - amount: " + toSellProduct.getAmount() +
//							"\nRevenue: " + revenue + " - old price: " + itemCost + " - new product price: " + newItemCost);
					
					Utils.sendMessageWithConcept(ACLMessage.INFORM, codec, ontology, msg.getSender(),
							Constants.SELL_PRODUCT, this.agMarket, toSellProductResponse);
			}

		}else{
			block();
		}



	}
	
	AgMarket agMarket;
	Codec codec;
	Ontology ontology;

}
